<template>
  <div>
    <!-- 搜索 -->
    <el-form :inline=true class="query-box">
      <el-form-item label="角色名称">
        <el-input v-model="queryForm.roleName" placeholder="请输入角色名称" class="handle-input"></el-input>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
    </el-form>
    <div class="option-box">
      <el-button type="primary" v-has="'role:add'" @click="addRole">添加</el-button>
    </div>

    <el-table :data="tableData" stripe style="width: 100%" ref="multipleTable"
      v-loading="tableLoading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading">
      <el-table-column type="selection" />
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" v-has="'role:update'" @click="editRole(scope.$index, scope.row)">编辑</el-button>
          <el-button type="text" v-has="'role:setAuth'" @click="openAuth(scope.row)">功能权限</el-button>
          <el-button type="text" v-has="'role:dataScope'" @click="openDataScope(scope.row)">数据权限</el-button>
          <el-button type="text" class="text-button-del" v-has="'role:delete'" @click="delRole(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination @current-change="pageChange" layout="prev, pager, next"
        :current-page="queryForm.pageNum" :page-size="queryForm.pageSize" :total="totalNum">
      </el-pagination>
    </div>

    <!--dialog弹窗 添加/修改-->
    <el-dialog :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :modal-append-to-body=false
      :close-on-click-modal=false
      :close-on-press-escape=false>
      <el-form ref="roleForm" :model="roleForm" :inline=true :rules="roleFormRules" label-position="right" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="roleForm.remark" placeholder="请输入备注" class="handle-textarea"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading"  @click="roleFormSubmit">提 交</el-button>
      </span>
    </el-dialog>

    <!--dialog弹窗 设置功能权限-->
    <el-dialog :title="authTree.dialogTitle"
      :visible.sync="authTree.dialogVisible"
      width="35%"
      :modal-append-to-body=false
      :close-on-click-modal=false
      :close-on-press-escape=false
      @close="handlerAuthClose">
      <el-form label-position="right" label-width="80px">
        <el-form-item label="角色名称">
          <el-input :disabled="true" v-model="authTree.roleName" placeholder="请输入角色名称" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="功能权限">
          <el-tree
            :props="authTree.props"
            :data="authTree.authTreeData"
            :default-checked-keys="authTree.selectIds"
            show-checkbox
            :default-expand-all=false
            node-key="id"
            ref="authTree">
          </el-tree>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="authTree.dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading"  @click="setAuth">提 交</el-button>
      </span>
    </el-dialog>

    <!--dialog弹窗 设置数据权限-->
    <el-dialog :title="dataScope.dialogTitle"
      :visible.sync="dataScope.dialogVisible"
      width="35%"
      :modal-append-to-body=false
      :close-on-click-modal=false
      :close-on-press-escape=false
      @close="handlerDataScopeClose">

      <el-form label-position="right" label-width="80px">
        <el-form-item label="角色名称">
          <el-input :disabled="true" v-model="dataScope.roleName" placeholder="请输入角色名称" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="数据权限">
          <el-tree
            :props="dataScope.props"
            :data="dataScope.deptTreeData"
            :default-checked-keys="dataScope.selectIds"
            show-checkbox
            :default-expand-all="true"
            node-key="id"
            ref="deptTree">
          </el-tree>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dataScope.dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading"  @click="setDataScope">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as role from '@/api/role'
import {mapGetters} from 'vuex'

export default {
  name: 'RoleList',
  data () {
    return {
      role,
      queryForm: {
        roleName: '',
        pageNum: this.GLOBAL.pageNum,
        pageSize: this.GLOBAL.pageSize
      },
      roleForm: {
        id: '',
        roleName: '',
        remark: ''
      },
      authTree: {
        dialogVisible: false,
        dialogTitle: '设置功能权限',
        authTreeData: [],
        roleName: '',
        props: {
          children: 'children',
          label: 'authName'
        },
        form: {
          roleId: '',
          authIds: []
        },
        selectIds: []
      },
      dataScope: {
        dialogVisible: false,
        dialogTitle: '设置数据权限',
        roleName: '',
        deptTreeData: [],
        selectIds: [],
        props: {
          children: 'children',
          label: 'deptName'
        },
        form: {
          roleId: '',
          deptIds: []
        }
      },
      dialogVisible: false, // 弹窗
      dialogTitle: '', // 弹窗标题
      isEdit: false, // 是否为修改操作
      totalNum: 1, // 总页数
      tableData: [], // 表格数据
      tableLoading: true,
      loading: false,

      roleFormRules: {
        roleName: [{required: true, message: '角色不能为空', trigger: 'blur'}],
        remark: [{max: 200, message: '最多200个字符', trigger: 'blur'}]
      }
    }
  },
  methods: {
    pageChange (val) {
      this.queryForm.pageNum = val;
      this.queryList();
    },
    transformDict (key, code) {
      return this.dictinfo(key, code);
    },
    search () {
      // this.pageNum = this.GLOBAL.pageNum;
      this.queryList();
    },
    queryList () {
      let param = this.GLOBAL.handlerQueryParam({
        ...this.queryForm
      });
      role.roleList(param).then(res => {
        this.tableData = res.data.list;
        this.totalNum = Number(res.data.total);
        this.tableLoading = false;
      });
    },
    addRole () {
      this.isEdit = false;
      this.dialogTitle = '添加';
      this.GLOBAL.clearObject(this.roleForm);
      this.dialogVisible = true;
    },
    editRole (index, row) {
      this.isEdit = true;
      this.dialogTitle = '编辑';
      this.GLOBAL.clearObject(this.roleForm);
      role.roleDetail(row.id).then(res => {
        this.roleForm = res.data;
        this.dialogVisible = true;
      });
    },
    delRole (index, row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          role.delRole(row.id)
            .then(res => {
              this.$message.success('删除成功');
              this.queryList();
            });
        })
    },
    roleFormSubmit () {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let param = this.GLOBAL.handlerQueryParam({
            ...this.roleForm
          });
          if (this.isEdit) {
            role.editRole(param)
              .then(res => {
                this.loading = false;
                this.dialogVisible = false;
                this.queryList();
              })
              .catch(() => {
                this.loading = false;
              })
          } else {
            role.addRole(param)
              .then(res => {
                this.loading = false;
                this.dialogVisible = false;
                this.queryList();
              })
              .catch(() => {
                this.loading = false;
              });
          }
        }
      });
    },
    openAuth (row) {
      role.roleAuth(row.id).then(res => {
        this.authTree.authTreeData = [...res.data.authTree];
        this.authTree.form.roleId = row.id;
        this.authTree.roleName = row.roleName;
        this.authTree.selectIds = this.filterSelectChild(res.data.authTree, [...res.data.roleAuthId]);
        this.authTree.dialogVisible = true;
      });
    },
    filterSelectChild (treeData, selectArr) {
      let result = [];
      treeData.forEach(ele => {
        if (ele.children.length > 0) {
          let res = this.filterSelectChild(ele.children, selectArr, result);
          if (res.length > 0) {
            result.push(...res);
          }
        } else {
          if (selectArr.find((value) => {
            return value === ele.id;
          })) {
            result.push(ele.id);
          }
        }
      });
      return result;
    },
    handlerAuthClose () {
      this.authTree.authTreeData = [];
      this.authTree.selectIds = [];
    },
    setAuth () {
      var checked = [];
      checked.push(...this.$refs.authTree.getCheckedKeys());
      checked.push(...this.$refs.authTree.getHalfCheckedKeys());
      this.authTree.form.authIds = checked;
      this.loading = true;
      role.setAuth(this.authTree.form).then(res => {
        this.authTree.dialogVisible = false;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      })
    },
    openDataScope (row) {
      role.getRoleDept(row.id).then(res => {
        this.dataScope.deptTreeData = [...res.data.deptTree];
        this.dataScope.roleName = row.roleName;
        this.dataScope.form.roleId = row.id;
        this.dataScope.selectIds = this.filterSelectChild(this.dataScope.deptTreeData, [...res.data.roleDeptIds]);
        this.dataScope.dialogVisible = true;
      });
    },
    handlerDataScopeClose () {
      this.dataScope.selectIds = [];
    },
    setDataScope () {
      let checked = [];
      checked.push(...this.$refs.deptTree.getCheckedKeys());
      checked.push(...this.$refs.deptTree.getHalfCheckedKeys());
      this.dataScope.form.deptIds = checked;
      this.loading = true;
      role.setDept(this.dataScope.form).then(res => {
        this.dataScope.dialogVisible = false;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      })
    }
  },
  created () {
    this.queryList();
  },
  computed: {
    ...mapGetters(['menu'])
  },
  watch: {
    dialogVisible (val, oldValue) {
      if (val && this.$refs.roleForm !== undefined) {
        this.$refs.roleForm.resetFields();
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
